<template>
    <div class="edu-page-warp">
        <condition-card
            :showResetBtn="true"
            @search="searchList"
            @reset="reset"
            label-width="100px"
        >
            <el-row>
                <el-col :span="8">
                    <el-form-item :label="$t('label.grade')">
                        <!-- <GradeSelect v-model="queryParams.grade" :showAll="false"></GradeSelect> -->
                        <el-date-picker
                            style="width:100%"
                            v-model="queryParams.grade"
                            align="right"
                            type="year"
                            value-format="yyyy"
                            placeholder="请选择"
                            :clearable="true">
                        </el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item :label="$t('school.schoolName')">
                        <el-input v-model="queryParams.condition"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
        </condition-card>
        <el-card shadow="never">
            <div class="edu-page-title">{{$t('school.schoolList')}}</div>
            <div class="edu-opertion-bar">
                <div class="float-right">
                    <el-button @click="updateRecord(null)" type="primary">{{$t('common.btn.add')}}</el-button>
                    <!-- <el-button @click="asyncSchool" type="primary">同步学堂到学籍</el-button> -->
                </div>
            </div>
            <edu-table
                ref="mainTable"
                url="/api/welcomeservice/tutorSchool/list"
                :order="false"
                :selection="false"
            >
                <el-table-column :label="$t('label.grade')" prop="grade"/>
                <el-table-column :label="$t('school.schoolName')" prop="name"/>
                <el-table-column
                    :label="$t('school.describe')"
                    prop="describe"
                    show-overflow-tooltip
                />
                <el-table-column :label="$t('message.operating')" fixed="right">
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            @click="updateRecord(scope.row)"
                            size="mini"
                        >{{$t('message.edit')}}</el-button>
                        <el-button
                            type="text"
                            @click="deleteRecord(scope.row)"
                            size="mini"
                        >{{$t('message.delete')}}</el-button>
                        <el-button
                            type="text"
                            @click="detail(scope.row)"
                            size="mini"
                        >{{$t('message.detail')}}</el-button>
                    </template>
                </el-table-column>
            </edu-table>
        </el-card>
        <!--  编辑和新增 -->
        <edu-dialog
            :title="dialogTitle"
            width="50%"
            ref="updateDialog"
            :showButtons="showBtn"
            :auto-height="true"
            @close="resetForm"
            @confirm="submitForm"
        >
            <div class="edu-page-warp">
                <el-form :model="createForm" ref="createForm" label-width="100px" label-suffix=":">
                    <el-row>
                        <el-col :span="8">
                            <el-form-item
                                :label="$t('label.grade')"
                                prop="grade"
                                :rules="[{ required: true, message: $t('message.inputRequired'), trigger: 'blur' }]"
                            >
                                <GradeSelect v-model="createForm.grade" :showAll="false" :disabled="!showBtn"></GradeSelect>
                                <!-- <el-date-picker
                                    style="width:100%"
                                    v-model="createForm.grade"
                                    align="right"
                                    type="year"
                                    value-format="yyyy"
                                    placeholder="请选择"
                                    :clearable="true">
                                </el-date-picker> -->
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item
                                :label="$t('school.schoolName')"
                                prop="name"
                                :rules="[{ required: true, message: $t('message.inputRequired'), trigger: 'blur' }]"
                            >
                                <el-input
                                    v-model="createForm.name"
                                    :disabled="!showBtn"
                                    maxlength="32"
                                ></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="24">
                            <el-form-item
                                :label="$t('school.describe')"
                                prop="describe"
                                :rules="[{ required: true, message: $t('message.inputRequired'), trigger: 'blur' }]"
                            >
                                <el-input
                                    :disabled="!showBtn"
                                    type="textarea"
                                    :autosize="{ minRows: 2, maxRows: 4}"
                                    v-model="createForm.describe"
                                    maxlength="255"
                                    show-word-limit
                                ></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-form-item class="float-right no-bottom no-right">
                        <el-button :disabled="!showBtn" @click="addRow">{{$t('message.add')}}</el-button>
                    </el-form-item>
                </el-form>
                <el-table :data="createForm.tutorSchoolProfessionList" size="mini" stripe>
                    <el-table-column :label="$t('school.professionalCategory')">
                        <template slot-scope="scope">
                            <el-select
                                v-model="scope.row.professionCode"
                                filterable
                                :disabled="!showBtn"
                            >
                                <el-option
                                    v-for="item in options.major"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                ></el-option>
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('类型')">
                        <template slot-scope="scope">
                            <dict-select
                                v-model="scope.row.mode"
                                :data="options.modes"
                                :disabled="!showBtn"/>
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('nonPublicCourseOpen.operation')">
                        <template slot-scope="scope">
                            <el-button
                                :disabled="!showBtn"
                                type="text"
                                @click="deleteRow(scope.$index)"
                                size="mini"
                            >{{$t('message.delete')}}</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </edu-dialog>

        <!--  同步学堂到学籍 -->
        <edu-dialog
            title="同步学堂到学籍"
            width="45%"
            :visible.sync="showDeptsDialog"
            ref="syncDialog"
            @close="resetSyncForm"
            @confirm="submitSyncForm"
        >
            <el-form
                :model="createSyncForm"
                ref="createSyncForm"
                label-width="85px"
                :rules="rules"
                class="createForm"
                label-position="right"
            >
                <el-row>
                    <el-col :span="11">
                        <el-form-item label="入学年级" prop="grade">
                            <grade-select :showAll="false" v-model="createSyncForm.grade"></grade-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="当前年级" prop="grade">
                            <grade-select :showAll="false" v-model="createSyncForm.currentGrade"></grade-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </edu-dialog>
    </div>
</template>
<script>
import { queryDic } from "common/src/api/dictionary";
import APIs from "common/src/api/welcomeService/schoolRelation";
import CPIs from "common/src/api/welcomeService/tutorExportImport";
import UTILS from "common/src/utils/utils";

// 学堂关系维护
var manualAddObj = {
    professionCode: "",
    mode:""
};
var defaultCreateForm = {
    grade: null,
    name: "",
    describe: "",
    ids: [],
    tutorSchoolProfessionList: [JSON.parse(JSON.stringify(manualAddObj))]
};
export default {
    name: "schoolRelationsMaintenance",
    mounted() {
        this.searchList();
        this.init();
    },
    watch: {
        "createForm.grade": {
            handler: function(newVal, oldVal) {
                if (newVal) {
                    this.getOptions(newVal);
                }
            }
        }
    },
    data() {
        return {
            options: {
                major: [],
                modes: []
            },
            showBtn: true,
            queryParams: {
                condition: "",
                grade: ""
            },
            dialogTitle: "",
            createForm: UTILS.clone(defaultCreateForm),
            createSyncForm: {
                grade: null,
                currentGrade: null
            },
            rules: {
                grade: [
                    {
                        required: true,
                        message: this.$t("message.inputRequired"),
                        trigger: "change"
                    }
                ]
            }
        };
    },
    methods: {
        getOptions(val) {
            //筛选条件字典查询
            APIs.findSchoolProfession(val).then(res => {
                this.options.major = [];
                for (const item of res.data) {
                    this.options.major.push({
                        value: item.professionCateGory,
                        label: item.professionCateGoryName+" ("+item.professionCateGory+")"
                    });
                }
            });
            //筛选条件字典查询
            /* let data = {
        lang: this.$store.getters.language || "cn",
        type: "allChild",
        keys: [
          "G_ZY"
        ]
      };

      queryDic(data).then(res => {
        UTILS.fillSelect(
            {
              major: "G_ZY"
            },
            res.data,
            this.options
        );
      }) */
            // this.searchList();
        },
        init() {
            //筛选条件字典查询
            let data = {
                lang: this.$store.getters.language || "cn",
                type: "allChild",
                keys: ["X_ZYDLLX"]
            };
            queryDic(data).then(res => {
                if (res.code == 200) {
                    UTILS.fillSelect(
                        {
                            modes: "X_ZYDLLX"
                        },
                        res.data,
                        this.options
                    );
                }
            });
        },
        reset() {
            this.queryParams.condition = "";
            this.queryParams.grade = "";
            this.searchList();
        },
        resetForm() {
            this.$refs.createForm.clearValidate();
            this.searchList();
        },
        searchList() {
            this.$refs.mainTable.search(this.queryParams);
        },
        updateRecord(data) {
            this.showBtn = true;
            if (!data) {
                //新增
                this.dialogTitle = this.$t("message.add");
                this.createForm = UTILS.clone(defaultCreateForm);
            } else {
                this.dialogTitle = this.$t("message.edit");
                APIs.findSchoolById(data.id).then(res => {
                    if (res.code == 200) {
                        this.createForm = res.data;
                    }
                });
            }
            this.$refs.updateDialog.open();
        },
        detail(data) {
            this.dialogTitle = this.$t("message.detail");
            APIs.findSchoolById(data.id).then(res => {
                if (res.code == 200) {
                    this.createForm = res.data;
                }
            });
            this.showBtn = false;
            this.$refs.updateDialog.open();
        },
        addRow() {
            this.createForm.tutorSchoolProfessionList.push(
                JSON.parse(JSON.stringify(manualAddObj))
            );
        },
        deleteRow(data) {
            this.$delConfirm().then(() => {
                let tempList = [];
                this.createForm.tutorSchoolProfessionList.forEach(
                    (value, index) => {
                        if (data != index) {
                            tempList.push(value);
                        }
                    }
                );
                this.createForm.tutorSchoolProfessionList = tempList;
            })            
        },
        submitForm() {
            this.$refs.createForm.validate(valid => {
                if (valid) {
                    let item = UTILS.clone(this.createForm);
                    if (UTILS.isNotEmpty(item.tutorSchoolProfessionList)) {
                        for (const data of item.tutorSchoolProfessionList) {
                            if (!data.professionCode) {
                                this.$message({
                                    type: "warning",
                                    message: "已经添加的专业大类不能为空"
                                });
                                return;
                            }
                            if (!data.mode) {
                                this.$message({
                                    type: "warning",
                                    message: "已经添加的专业大类类型不能为空"
                                });
                                return;
                            }
                        }
                    }
                    if (item.id) {
                        //编辑
                        APIs.editSchool(item).then(res => {
                            if ((res.code = 200)) {
                                this.$message({
                                    type: "success",
                                    message: this.$t("message.editSuccess")
                                });
                                this.$refs.updateDialog.close();
                                this.searchList();
                            }
                        });
                    } else {
                        //新增
                        APIs.addSchool(item).then(res => {
                            if ((res.code = 200)) {
                                this.$message({
                                    type: "success",
                                    message: this.$t("message.addSuccess")
                                });
                                this.$refs.updateDialog.close();
                                this.searchList();
                            }
                        });
                    }
                }
            });
        },
        deleteRecord(data) {
            let ids = [];
            ids.push(data.id);
            this.createForm.ids = ids;
            this.$delConfirm().then(() => {
                APIs.deleteSchool(this.createForm).then(res => {
                    if ((res.code = 200)) {
                        this.$message({
                            type: "success",
                            message: this.$t("common.tips.deleteSuccess")
                        });
                        this.searchList();
                    }
                });
            });
        },

        /* 同步学堂到学籍 */
        asyncSchool() {
            this.$refs.syncDialog.open();
        },
        submitSyncForm() {
            this.$refs.createSyncForm.validate(valid => {
                if (!valid) {
                    return;
                }
                let loading = this.$loading({
                    lock: true,
                    text: "Loading",
                    spinner: "el-icon-loading",
                    background: "rgba(255, 255, 255, .48)"
                });
                APIs.syncSchool(this.createSyncForm).then(res => {
                    if (res.code == 200) {
                        this.delayRequest(res.data.key, loading);
                    } else {
                        loading.close();
                    }
                });
            });
        },

        // 	handleExportSchemes() {
        // 	this.exportResult = null;
        // 	this.$refs.downloadRef.open();
        // 	this.exportButton = true;
        // 	exportList(this.queryParams.condition).then(res => {
        // 		if (res.code == 200) {
        // 			this.delayRequest(res.data.key);
        // 		} else {
        // 			this.$refs.downloadRef.close();
        // 			this.exportButton = false;
        // 		}
        // 	});
        // },

        //异步获取批量结果
        delayRequest(key, loading) {
            setTimeout(() => {
                CPIs.getImportStatus(key)
                    .then(res => {
                        // this.exportResult = res.data;
                        if (res.code == 200 && res.data.status) {
                            if (res.data.success) {
                                this.$message({
                                    type: "success",
                                    message: "同步成功"
                                });
                                loading.close();
                                this.searchList();
                            } else {
                                this.$message({
                                    type: "error",
                                    message: res.data.msg
                                });
                            }
                        } else {
                            this.delayRequest(key, loading);
                        }
                    })
                    .catch(ex => {
                        this.delayImportRequest(key, loading);
                    });
            }, 3000);
        },

        resetSyncForm() {
            this.createSyncForm.grade = null;
            this.createSyncForm.currentGrade = null;
            this.$refs.createSyncForm.clearValidate();
        }
    }
};
</script>
<style lang="scss" scoped>
.createForm {
    .line {
        text-align: center;
    }
    .el-date-editor.el-input,
    .el-date-editor.el-input__inner {
        width: 100%;
    }
    .el-select {
        width: 100%;
    }
}
</style>

